//用户登录与注册
import { reqGetCode, reqUserRegister,reqUserLogin,reqGetUserInfo,reqLogout } from "@/api";

//引入本地存储setToken
import {getToken, setToken,removeToken} from "@/utils/token"
const state = {
    //注册验证码
    code: "",
    //唯一标识符
    token:getToken(),
    //用户信息
    userInfo:{},
}
const mutations = {
    //注册验证码
    GETCODE(state, code) {
        state.code = code;
    },
    //用户登录
    USERLOGIN(state,token){
        state.token = token
    },
    //获取用户信息userInfo
    GETUSERINFO(state,userInfo){
      state.userInfo = userInfo;
    },
    //退出登录，清除用户信息
    CLEAR(state){
        //清除本地存储token
        removeToken();
        //清除vuex里的token
        state.token="";   
        //清除用户信息
        state.userInfo = {};
    }

}
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone);
        if (result.code == 200) {
            commit("GETCODE", result.data)
            return "ok"
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    //用户注册
    async UserRegister({ commit }, user) {
        let result = await reqUserRegister(user);
        if (result.code == 200) {
            return "ok";
        } else {
            return Promise.reject(new Error("faile"))
        }
    },

    //用户登录
    async userLogin({commit},data){
        let result = await reqUserLogin(data);
        //服务器派发token
        if(result.code==200){
            //用户登录成功且获取到token
            commit("USERLOGIN",result.data.token)
            ////引入本地存储setToken,持久化存储token
            setToken(result.data.token);
            return "ok"
        }else{
            return Promise.reject(new Error(result.message));
        }
    },
    //获取用户信息【需要携带token带给服务器，axios二次封装了】
    async getUserInfo ({commit}){
        let result = await reqGetUserInfo();
        if(result.code==200){
            commit("GETUSERINFO",result.data)
        }
    },
    //退出登录
    async Logout({commit}){
      let result = await reqLogout();
      if (result.code==200) {
          commit("CLEAR")
          return "ok"
      }else{
          return Promise.reject(result.data)
      } 
    }
}
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters
}